# coding=utf-8
from django import forms
from account.models import User


class RegisterForm(forms.ModelForm):
    error_messages = {
        'duplicate_email': '电子邮箱已经被人使用',
        'password_mismatch': '两次输入密码不匹配',
    }

    team = forms.CharField(label='团队名称', max_length=32)
    email = forms.EmailField(label='电子邮箱', help_text='邮箱就是登录帐号，我们不会把你的邮箱告诉别人。')
    nickname = forms.CharField(label='昵称', max_length=16)
    password1 = forms.CharField(label='密码', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('email', 'nickname')

    def clean_email(self):
        email = self.cleaned_data["email"]
        try:
            User._default_manager.get(email=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError(
            self.error_messages['duplicate_email'],
            code='duplicate_email',
        )

    def clear_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        return password2

    def save(self, commit=True):
        user = super(RegisterForm, self).save(commit=False)
        #user.is_active = False
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save
        return user


class ProfileForm(forms.ModelForm):
    nickname = forms.CharField(label='昵称', max_length=16)
    password1 = forms.CharField(label='密码', widget=forms.PasswordInput, required=False)

    class Meta:
        model = User
        fields = ('nickname',)

    def save(self, commit=True):
        user = super(ProfileForm, self).save(commit=False)
        if self.cleaned_data.get('password1'):
            user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save
        return user


class AvatarForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('avatar', )

    def save(self, commit=True):
        user = super(AvatarForm, self).save(commit=False)
        if commit:
            user.save
        return user
